<template>
  <div>
    <el-text :size="componentSize" type="info">
      <div v-if="showRefreshButton">
        <el-button
          class="refresh"
          :size="componentSize"
          type="primary"
          @click="start"
          >刷新</el-button
        >
        <el-text class="margin-left20">
          <el-icon>
            <InfoFilled />
          </el-icon>
          点击题目进入比赛答题
        </el-text>
      </div>
      <div v-else>
        <el-icon>
          <InfoFilled />
        </el-icon>
        点击题目进入比赛答题
      </div>
    </el-text>
    <el-table
      :size="componentSize"
      row-class-name="cursor-pointer"
      class="match-question-table"
      :max-height="`calc(100vh - 64px - var(--container-margin)* 5 - var(--container-header-height))`"
      :data="tableData"
      style="width: 100%"
      @row-click="handleRowClick"
    >
      <template v-slot:empty>
        <el-empty
          image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png"
        />
      </template>
      <el-table-column prop="name" label="题号" width="80">
        <template #default="{ row, column, $index }">
          #{{ row.paixu + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="type" label="题型" width="80"></el-table-column>
      <el-table-column prop="score" label="满分" width="100"></el-table-column>
      <el-table-column
        prop="-"
        label="我的提交"
        width="100"
        :formatter="formatterMySubmit"
      >
      </el-table-column>
      <el-table-column prop="name" label="题目名称" width="">
        <template #default="{ row, column, $index }">
          {{
            !activity.isshowquestionname && row.type === "代码"
              ? `第${row.paixu + 1}题`
              : row.name
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop=""
        label="我的代码"
        width=""
        v-if="showMyCodeColumn"
      >
        <template #default="{ row }">
          <el-button
            v-if="row.type === '代码'"
            type="primary"
            :size="componentSize"
            @click.stop="showMyCode(row)"
          >
            查看代码
          </el-button>
          <el-button
            v-if="row.type === '代码' && showSupplementButton && isActivityEnd"
            type=""
            :size="componentSize"
            @click.stop="toQuestion(row)"
          >
            去补题
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" width="60%" :before-close="handleClose">
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          {{ sourceDetail.userName }} - {{ sourceDetail.name }}-代码详情
        </span>
      </template>
      <el-row class="dialog-content">
        <el-col :span="24" class="right">
          <el-row class="source-code-title">
            <h6 class="margin-bottom0">源代码</h6>
            <div class="margin-left10">
              <el-icon
                class="icon cursor-pointer"
                @click="myCopy(sourceDetail.sourceCode || '')"
              >
                <CopyDocument />
              </el-icon>
            </div>
          </el-row>
          <div class="col p-0">
            <pre v-highlight :class="'language-' + sourceDetail.sourceLanguage">
                    <code v-text="sourceDetail.sourceCode" class="code-pre"></code>
                </pre>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <el-button
          type="primary"
          :size="componentSize"
          @click="dialogVisible = false"
          >关闭</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useClipboard } from "@vueuse/core";
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, onMounted, reactive, ref, toRefs, watch } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { SHOW_AC_STATUS } from "../admin/views/data";
import {
  asyncgetactivityduration,
  asyncselectmatchquestion,
  asyncselectmatchuserquestion,
  asyncteamselectmatchuserquestion,
} from "../api";
import { Storekey } from "../interface";
import Studycodemodel from "../mysql_interface/studycodemodel";

const { text, copy, copied, isSupported } = useClipboard();

// 组件配置类型
type ComponentVariant = "acCoderSaas" | "acCoderH5" | "mathH5" | "ojSass";

type Props = {
  activity: Studycodemodel.Iactivity;
  setduration: (data: {
    activityendtime: Date;
    activitystarttime: Date;
  }) => void;
  variant?: ComponentVariant;
  isnot?: { err: number; msg: string };
};

const props = withDefaults(defineProps<Props>(), {
  variant: "acCoderSaas",
});

const emit = defineEmits(["rowClick"]);

const router = useRouter();
const store = useStore(Storekey);

// 根据变体决定组件配置
const componentConfig = computed(() => {
  const configs = {
    acCoderSaas: {
      size: "default" as const,
      showRefreshButton: false,
      showMyCodeColumn: true,
      showSupplementButton: false,
      useEmitRowClick: false,
      needsMatchQuestion: false,
      skipRegistrationCheck: false,
    },
    acCoderH5: {
      size: "small" as const,
      showRefreshButton: false,
      showMyCodeColumn: true,
      showSupplementButton: false,
      useEmitRowClick: false,
      needsMatchQuestion: false,
      skipRegistrationCheck: false,
    },
    mathH5: {
      size: "default" as const,
      showRefreshButton: true,
      showMyCodeColumn: true,
      showSupplementButton: true,
      useEmitRowClick: false,
      needsMatchQuestion: true,
      skipRegistrationCheck: true,
    },
    ojSass: {
      size: "default" as const,
      showRefreshButton: true,
      showMyCodeColumn: true,
      showSupplementButton: true,
      useEmitRowClick: true,
      needsMatchQuestion: true,
      skipRegistrationCheck: false,
    },
  };
  return configs[props.variant];
});

const componentSize = computed(() => componentConfig.value.size);
const showRefreshButton = computed(
  () => componentConfig.value.showRefreshButton
);
const showMyCodeColumn = computed(() => componentConfig.value.showMyCodeColumn);
const showSupplementButton = computed(
  () => componentConfig.value.showSupplementButton
);

const user = computed(() => {
  return store.state.user;
});

const teamId = computed(() => {
  return user.value?.teamid;
});

const format = computed(() => {
  return props.activity.format;
});

const showScore = computed(() => {
  return (
    props.activity?.show_ac_status === SHOW_AC_STATUS.SHOW_SCORE ||
    props.activity?.show_ac_status === SHOW_AC_STATUS.SHOW_DETAILED_SCORE
  );
});

const datenow = computed(() => {
  return store.state.time;
});

// 比赛是否结束
const isActivityEnd = computed(() => {
  if (props.activity.activityendtime) {
    return new Date(props.activity.activityendtime).getTime() < datenow.value!;
  }
  return false;
});

onMounted(() => {
  start();
});

// tableData
const tableData = computed(() => {
  return actQuestions.value.map((e) => {
    let userQuestion = userQuestions.value.find((uq) => uq.questionid === e.ID);
    return {
      ...e,
      userQuestion,
    };
  });
});

// 我的提交
function formatterMySubmit(row: any) {
  let ret = "未提交";
  const { userQuestion, type } = row;
  if (userQuestion) {
    ret = "已提交";
    if (showScore.value && format.value === "IOI" && type === "代码") {
      // 1、有提交但是df为null
      ret = userQuestion?.df || 0;
    } else if (
      props.variant === "mathH5" &&
      format.value === "IOI" &&
      type === "代码"
    ) {
      // mathH5 变体不需要 showScore 检查
      ret = userQuestion?.df || 0;
    }
  }
  return ret;
}

// 比赛题目
const actQuestions = ref<Studycodemodel.Iquestion[]>([]);
const matchQuestion = ref<Studycodemodel.Imatchquestion[]>([]);
const userQuestions = ref<Studycodemodel.Imatchuserquestion[]>([]);

watch(
  () => props.activity.ID,
  (v) => {
    if (v) start();
  }
);

async function start() {
  const { question, activity, userquestion } =
    await asyncselectmatchuserquestion({
      ID: props.activity.ID!,
      my: true,
    });
  userQuestions.value = userquestion;

  if (componentConfig.value.needsMatchQuestion) {
    // 需要获取比赛题目详情的变体
    await selectmatchquestion();
    actQuestions.value = question.map((actQ) => {
      const matchQ = matchQuestion.value.find((mq) => mq.ID === actQ.ID);
      return { ...actQ, oldid: matchQ?.oldid };
    });
  } else {
    // 直接使用题目数据的变体
    actQuestions.value = question;
  }
}

async function selectmatchquestion() {
  const [data] = await asyncselectmatchquestion({
    activityid: props.activity.ID!,
  });
  matchQuestion.value = data.matchquestion || [];
}

// 最后一次校验是否可以参赛
const isnot = computed(() => {
  // 如果外部传递了 isnot，使用外部的
  if (props.isnot) {
    return props.isnot;
  }

  const { activitystarttime, activityendtime } = toRefs(props.activity);
  const start = activitystarttime?.value;
  const stop = activityendtime?.value;

  // 如果比赛没有开始
  if ((datenow.value || 0) < new Date(start ? start : "").getTime()) {
    return { err: 4, msg: "比赛还没有开始" };
  }
  // 如果比赛已结束
  if ((datenow.value || 0) > new Date(stop ? stop : "").getTime()) {
    return { err: 5, msg: "比赛已结束" };
  }
  if (!user) {
    return { err: 1, msg: "没有登录，请登录" };
  }

  // mathH5 变体跳过报名检查
  if (componentConfig.value.skipRegistrationCheck) {
    return { err: 0, msg: "" };
  }

  const my = props.activity.activityuser?.find(
    (v) => v.userid === user.value?.ID
  );
  if (!my) {
    if (props.activity.teamid) {
      const team = store.state.team?.rows.find(
        (e) => e.ID === props.activity.teamid
      );
      if (!team) {
        return { err: 3, msg: "你没有报名，请先报名" };
      }
    } else {
      return { err: 3, msg: "你没有报名，请先报名" };
    }
  }
  const t = userQuestions.value.find((v) => v.userid === user.value?.ID);
  if (t && format.value !== "IOI") {
    return { err: 2, msg: "你已经参加了比赛" };
  }
  return { err: 0, msg: "" };
});

// 点击题目处理
function handleRowClick(row: any) {
  if (componentConfig.value.useEmitRowClick) {
    // ojSass 变体使用 emit
    emit("rowClick", row);
    return;
  }

  // 其他变体的处理逻辑
  rowClick(row);
}

// 点击题目跳转比赛
function rowClick(row: any) {
  if (isnot.value.err) {
    ElMessage.warning(isnot.value.msg);
    return;
  }
  // 个人计时
  if (props.activity.duration) {
    ElMessageBox.confirm(
      `是否开始答题？开始后答题时间为${props.activity.duration}分钟,规定时间内必须提交答案，超时后将无法进入比赛`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(async (e) => {
        // 更新比赛时长(个人计时)
        const data = await asyncgetactivityduration({
          activityid: props.activity.ID || 0,
          isstart: true,
        });
        props.setduration(data);
        const routeData = router.resolve({
          name: "比赛答题",
          params: {
            ID: props.activity.ID,
            index: row.paixu || 0,
          },
        });
        window.open(routeData.href, "_blank");
      })
      .catch((f) => {
        ElMessage.error(f);
      });
  } else {
    const routeData = router.resolve({
      name: "比赛答题",
      params: {
        ID: props.activity.ID,
        index: row.paixu || 0,
      },
    });
    window.open(routeData.href, "_blank");
  }
}

// 补题-新开标签页
function toQuestion(row: any) {
  const url = router.resolve({
    name: "题目",
    params: { ID: row.oldid },
    query: {
      teamid: teamId.value,
      activityid: props.activity.ID,
    },
  });
  window.open(url.href, "_blank");
}

// 弹窗处理
function handleClose(done: () => void) {
  dialogVisible.value = false;
  done();
}

// 点击查看代码
const dialogVisible = ref(false);
const sourceDetail = reactive({
  userName: user.value?.name || "",
  name: "",
  score: "",
  testScores: [],
  sourceCode: "",
  sourceLanguage: "",
});

async function showMyCode(item: Studycodemodel.Iquestion) {
  if (item.type === "代码") {
    try {
      const { rows } = await asyncteamselectmatchuserquestion({
        userid: user.value?.ID,
        questionid: item.ID,
        activityid: props.activity.ID,
        teamid: props.activity.teamid || teamId.value,
      });
      if (rows.length) {
        const { context, language, matchquestion, user } = rows[0];
        sourceDetail.name = matchquestion?.name || "";
        sourceDetail.userName = user?.name || "";
        sourceDetail.sourceLanguage = language || "";
        sourceDetail.sourceCode = context || "";

        dialogVisible.value = true;
      } else {
        ElMessage.error("没有找到此题答题记录");
      }
    } catch (e) {
      ElMessage.error(e as any);
    }
  } else {
    ElMessage.error("此题不是代码题");
  }
}

function myCopy(str: string) {
  try {
    str ? copy(str) : "";
    ElMessage.success("复制成功");
  } catch (error) {
    console.error("myCopy error=>", str, error);
  }
}
</script>

<style scoped>
.match-question-table {
  /* 高度计算需要重构 */
  /* height: calc(100vh - 64px - var(--container-margin)* 5 - var(--container-header-height)); */
  margin: 0;
}
</style>
